package cn.school.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author oldliu
 * @since 1.0
 */
public class MybatisUtil {
    private static SqlSessionFactory sessionFactory ;

    private MybatisUtil(){

    }
    // 创建sessionFactory对象，因为整个应用程序只需要一个实例对象，故用静态代码块
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回sessionFactory对象 工厂对象
     *
     * @return sessionFactory
     */
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 新建session会话，并把session放在线程变量中
     */
    public static SqlSession get() {
        // 打开一个session会话
        SqlSession session = sessionFactory.openSession();
        return session;
    }
    public static SqlSession get(boolean autoCommit) {
        // 打开一个session会话
        SqlSession session = sessionFactory.openSession(autoCommit);
        return session;
    }

    public static void close(SqlSession session){
        //如果session对象不为空，关闭sessoin对象，并清空线程变量
        if(session!=null){
            session.commit();
            session.close();
        }
    }

}
